package bothWay;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author： pang-yun
 * @date： 2021-09-14 14:39
 * 功能目的 ：用于
 */

public class BothServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                        ByteBuf buffer = ctx.alloc().buffer();
                                        buffer.writeBytes("Hello, this is Server".getBytes(StandardCharsets.UTF_8));
                                        ctx.writeAndFlush(buffer);
                                    }

                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf byteBuf= msg instanceof ByteBuf ? ((ByteBuf) msg) : null;
                                        String string = byteBuf.toString(Charset.defaultCharset());
                                        System.out.println(string);

                                        ByteBuf buffer = ctx.alloc().buffer();
                                        buffer.writeBytes(("input: "+string).getBytes(StandardCharsets.UTF_8));
                                        ctx.writeAndFlush(buffer);
                                    }
                                });
                            }
                        }
                ).bind(9999);
    }
}
